{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "42bcbfc9-e0bb-4748-b47b-eee74d12b50a",
   "metadata": {},
   "source": [
    "# LangChain 核心模块 Agent - OpenAI Function\n"
   ]
  },
  {
   "cell_type": "code",
   "id": "146126a2-ab3c-4b83-a332-0d5dabe92425",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-13T07:41:54.243647Z",
     "start_time": "2024-07-13T07:41:52.270869Z"
    }
   },
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "# 使用 GPT-3.5-turbo\n",
    "llm = ChatOpenAI(temperature=0)"
   ],
   "outputs": [],
   "execution_count": 1
  },
  {
   "cell_type": "code",
   "id": "1042d527-cae8-4b6d-a767-39014e2f6d68",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-13T07:42:42.102700Z",
     "start_time": "2024-07-13T07:42:41.733104Z"
    }
   },
   "source": [
    "from langchain.agents import tool\n",
    "\n",
    "@tool\n",
    "def get_word_length(word: str) -> int:\n",
    "    \"\"\"Returns the length of a word.\"\"\"\n",
    "    return len(word)\n",
    "\n",
    "tools = [get_word_length]"
   ],
   "outputs": [],
   "execution_count": 2
  },
  {
   "cell_type": "code",
   "id": "54c7ba73-55fa-49cf-82cf-d310c1a8a0d1",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-13T07:43:07.568850Z",
     "start_time": "2024-07-13T07:43:07.553843Z"
    }
   },
   "source": [
    "from langchain.schema import SystemMessage\n",
    "from langchain.agents import OpenAIFunctionsAgent\n",
    "\n",
    "system_message = SystemMessage(content=\"你是非常强大的AI助手，但在计算单词长度方面不擅长。\")\n",
    "prompt = OpenAIFunctionsAgent.create_prompt(system_message=system_message)"
   ],
   "outputs": [],
   "execution_count": 3
  },
  {
   "cell_type": "code",
   "id": "ef0874c6-8076-4536-9533-bb9f69f450fe",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-13T07:43:18.453315Z",
     "start_time": "2024-07-13T07:43:18.234662Z"
    }
   },
   "source": [
    "agent = OpenAIFunctionsAgent(llm=llm, tools=tools, prompt=prompt)"
   ],
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "D:\\Dev\\anaconda3\\envs\\langchain\\lib\\site-packages\\langchain_core\\_api\\deprecation.py:119: LangChainDeprecationWarning: The class `OpenAIFunctionsAgent` was deprecated in LangChain 0.1.0 and will be removed in 0.3.0. Use create_openai_functions_agent instead.\n",
      "  warn_deprecated(\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "cell_type": "code",
   "id": "e7061c25-d090-4b52-a137-ba7545759241",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-13T07:44:10.215757Z",
     "start_time": "2024-07-13T07:44:10.204242Z"
    }
   },
   "source": [
    "from langchain.agents import AgentExecutor\n",
    "\n",
    "# 实例化 OpenAIFunctionsAgent\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)"
   ],
   "outputs": [],
   "execution_count": 5
  },
  {
   "cell_type": "code",
   "id": "4f0ae154-5cb9-44cf-91d6-cc80308dcffc",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-13T07:44:28.966295Z",
     "start_time": "2024-07-13T07:44:26.808286Z"
    }
   },
   "source": "agent_executor.run(\"单词“你好”中有多少个字母?\")",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
      "\u001B[32;1m\u001B[1;3m\n",
      "Invoking: `get_word_length` with `{'word': '你好'}`\n",
      "\n",
      "\n",
      "\u001B[0m\u001B[36;1m\u001B[1;3m2\u001B[0m\u001B[32;1m\u001B[1;3m单词“你好”中有2个字母。\u001B[0m\n",
      "\n",
      "\u001B[1m> Finished chain.\u001B[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'单词“你好”中有2个字母。'"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 7
  },
  {
   "cell_type": "code",
   "id": "2070d22f-c9d9-4346-b41d-e9beecb40625",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-13T07:48:18.396171Z",
     "start_time": "2024-07-13T07:48:18.374664Z"
    }
   },
   "source": [
    "from langchain.prompts import MessagesPlaceholder\n",
    "\n",
    "MEMORY_KEY = \"chat_history\"\n",
    "prompt = OpenAIFunctionsAgent.create_prompt(\n",
    "    system_message=system_message,\n",
    "    extra_prompt_messages=[MessagesPlaceholder(variable_name=MEMORY_KEY)]\n",
    ")"
   ],
   "outputs": [],
   "execution_count": 8
  },
  {
   "cell_type": "code",
   "id": "849ebeac-aa8c-4ae8-b36c-c81a120147fb",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-13T07:48:31.615510Z",
     "start_time": "2024-07-13T07:48:31.607447Z"
    }
   },
   "source": [
    "from langchain.memory import ConversationBufferMemory\n",
    "\n",
    "memory = ConversationBufferMemory(memory_key=MEMORY_KEY, return_messages=True)"
   ],
   "outputs": [],
   "execution_count": 9
  },
  {
   "cell_type": "code",
   "id": "9af06fad-4f85-4411-b4f8-4fca7a45e09b",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-13T07:48:41.045784Z",
     "start_time": "2024-07-13T07:48:41.035779Z"
    }
   },
   "source": [
    "agent = OpenAIFunctionsAgent(llm=llm, tools=tools, prompt=prompt)\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools, memory=memory, verbose=True)"
   ],
   "outputs": [],
   "execution_count": 10
  },
  {
   "cell_type": "code",
   "id": "fc912215-61d3-4ce1-9a48-b795cf445bde",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-13T07:49:33.682165Z",
     "start_time": "2024-07-13T07:49:31.170532Z"
    }
   },
   "source": "agent_executor.run(\"单词“hello”中有多少个字母?\")",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
      "\u001B[32;1m\u001B[1;3m\n",
      "Invoking: `get_word_length` with `{'word': 'hello'}`\n",
      "\n",
      "\n",
      "\u001B[0m\u001B[36;1m\u001B[1;3m5\u001B[0m\u001B[32;1m\u001B[1;3m单词“hello”中有5个字母。\u001B[0m\n",
      "\n",
      "\u001B[1m> Finished chain.\u001B[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'单词“hello”中有5个字母。'"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 16
  },
  {
   "cell_type": "code",
   "id": "d3f96ac9-b548-4908-9c5e-d58118ed6a9a",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-07-13T07:49:41.463931Z",
     "start_time": "2024-07-13T07:49:38.999029Z"
    }
   },
   "source": [
    "agent_executor.run(\"那是一个真实的单词吗？\")"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001B[1m> Entering new AgentExecutor chain...\u001B[0m\n",
      "\u001B[32;1m\u001B[1;3m是的，单词“hello”是一个真实的英语单词，表示“你好”或“喂”。请问您还有其他问题需要帮助吗？\u001B[0m\n",
      "\n",
      "\u001B[1m> Finished chain.\u001B[0m\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'是的，单词“hello”是一个真实的英语单词，表示“你好”或“喂”。请问您还有其他问题需要帮助吗？'"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 17
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2870681e-184f-4338-8cbb-3937e6bb33d0",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
